package com.zgh.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zgh.domain.*;
import com.zgh.mapper.*;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.java2d.pipe.SpanShapeRenderer;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BlogService {
    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BlogCommentMapper blogCommentMapper;

    @Autowired
    private BlogCollectionMapper blogCollectionMapper;

    @Autowired
    private BlogClassificationMapper blogClassificationMapper;

    @Autowired
    private UserCollectionMapper userCollectionMapper;

    @Autowired
    private ClassificationMapper classificationMapper;

    @Autowired
    private ProvinceMapper provinceMapper;

    /**
     * 查询所有博客
     *
     * @return 博客集合
     */
    public List<Blog> getAllBlogByTime(String order, String classifyName) {
        //根据时间获取所有博客
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        if (!"all".equals(classifyName)) {
            QueryWrapper<BlogClassification> blogClassificationQueryWrapper = new QueryWrapper<>();
            blogClassificationQueryWrapper.eq("classifyName", classifyName);
            List<BlogClassification> blogClassificationList = blogClassificationMapper.selectList(blogClassificationQueryWrapper);
            //根据分类查询博客
            if (blogClassificationList.size() != 0) {
                for (BlogClassification blogClassification : blogClassificationList) {
                    blogQueryWrapper.or().eq("id", blogClassification.getBlogId());
                }
            } else {
                return null;
            }
        }
        blogQueryWrapper.orderByDesc(order);
        List<Blog> blogList = blogMapper.selectList(blogQueryWrapper);
        //根据论坛userid查询用户信息
        for (Blog blog : blogList) {
            blog.setUser(userMapper.findUserById(blog.getUserId()));
            //根据blogId查询所属分类
            Map<String, Object> map = new HashMap<>();
            map.put("blogId", blog.getId());
            blog.setClassificationList(blogClassificationMapper.selectByMap(map));
        }
        return blogList;
    }

    /**
     * 根据id查询博客
     *
     * @param id 博客id
     * @return 博客
     */
    public Blog findBlogById(String id) {
        //条件构造器
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq("id", id);
        //查询论坛
        Blog blog = blogMapper.selectOne(blogQueryWrapper);
        blog.setViews(blog.getViews() + 1);
        blogMapper.updateById(blog);
        //根据博客userid查询用户信息
        blog.setUser(userMapper.findUserById(blog.getUserId()));
        //根据论坛id查询评论
        QueryWrapper<BlogComment> blogCommentWrapper = new QueryWrapper<>();
        blogCommentWrapper.eq("blogId", id);
        List<BlogComment> blogComments = blogCommentMapper.selectList(blogCommentWrapper);
        //根据评论用户id查询用户
        for (BlogComment blogComment : blogComments) {
            User user = userMapper.findUserById(blogComment.getUserId());
            blogComment.setUser(user);
        }
        blog.setBlogCommentList(blogComments);
        //根据id查询博客分类
        QueryWrapper<BlogClassification> blogClassificationQueryWrapper = new QueryWrapper<>();
        blogClassificationQueryWrapper.eq("blogId", blog.getId());
        List<BlogClassification> blogClassificationList = blogClassificationMapper.selectList(blogClassificationQueryWrapper);
        blog.setClassificationList(blogClassificationList);
        //System.out.println(blog);
        return blog;
    }

    /**
     * 点赞
     *
     * @param blogId     博客id
     * @param thumbCount 点赞数
     */
    public void thumb(String blogId, String thumbCount) {
        int thumb = Integer.parseInt(thumbCount);
        blogMapper.thumb(blogId, thumb);
    }

    /**
     * 收藏
     *
     * @param blogId   博客id
     * @param openId   openid
     * @param operator 操作 0插入 1删除
     */
    public void collect(String blogId, String openId, String operator) {
        UpdateWrapper<UserCollection> blogCollectionUpdateWrapper = new UpdateWrapper<>();
        User user = userMapper.findUserByOpenId(openId);
        if (operator.equals("0")) {
            //插入
            UserCollection blogCollection = new UserCollection();
            blogCollection.setBlogId(Integer.parseInt(blogId));
            blogCollection.setUserId(user.getId());
            blogCollection.setCollectionTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            blogCollectionMapper.insert(blogCollection);
        } else {
            //删除
            blogCollectionUpdateWrapper.eq("blogId", blogId).eq("userId", user.getId());
            blogCollectionMapper.delete(blogCollectionUpdateWrapper);
        }
        //更新博客表中的收藏字段
        int count = getCollectCountByBlogId(blogId);
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq("id", blogId);
        Blog blog = blogMapper.selectOne(blogQueryWrapper);
        LambdaUpdateWrapper<Blog> lambdaUpdateWrapper = new UpdateWrapper<Blog>().lambda();
        lambdaUpdateWrapper.eq(Blog::getId, blogId).set(Blog::getCollections, count);
        blogMapper.update(blog, lambdaUpdateWrapper);
    }

    /**
     * 获取当前用户的收藏博客集合
     *
     * @param openId openid
     * @return 收藏集合
     */
    public List<UserCollection> getBlogCollectList(String openId) {
        User user = userMapper.findUserByOpenId(openId);
        QueryWrapper<UserCollection> blogCollectionQueryWrapper = new QueryWrapper<>();
        blogCollectionQueryWrapper.eq("userId", user.getId());
        return blogCollectionMapper.selectList(blogCollectionQueryWrapper);
    }

    /**
     * 根据blogID查询收藏数量
     *
     * @param blogId blogId
     * @return 数量
     */
    public int getCollectCountByBlogId(String blogId) {
        QueryWrapper<UserCollection> blogCollectionQueryWrapper = new QueryWrapper<>();
        blogCollectionQueryWrapper.eq("blogId", blogId);
        return blogCollectionMapper.selectCount(blogCollectionQueryWrapper);
    }

    /**
     * 根据省份查询博客
     *
     * @param province 省份
     * @return 博客集合
     */
    public List<Blog> getAllBlogByProvince(String province) {
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq("provinceName", province)
                .orderByDesc("releaseTime")
                .last("limit 0,2");
        List<Blog> blogList = blogMapper.selectList(blogQueryWrapper);
        for (Blog blog : blogList) {
            //根据博客userid查询用户信息
            blog.setUser(userMapper.findUserById(blog.getUserId()));
        }
        return blogList;
    }

    /**
     * 上传博客
     *
     * @param blog1
     * @return 失败或成功
     */
    public int uploadBlog(Blog blog1) {
        String openid = blog1.getUser().getOpenid();
        LambdaUpdateWrapper<User> userLambdaUpdateWrapper = new UpdateWrapper<User>().lambda();
        userLambdaUpdateWrapper.eq(User::getOpenid, openid);
        User user1 = userMapper.selectOne(userLambdaUpdateWrapper);
        int userid = user1.getId();
        String author = user1.getNickname();
        blog1.setUserId(userid);
        blog1.setAuthor(author);
        blog1.setReleaseTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        HashMap<String, Object> map = new HashMap<>();
        map.put("province", blog1.getProvinceName());
        List<Province> provinces = provinceMapper.selectByMap(map);
        for (Province province : provinces) {
            blog1.setProvinceId(province.getId());
        }
        int pd = blogMapper.insert(blog1);
        BlogClassification blogClassification = new BlogClassification();
        blogClassification.setClassifyName(blog1.getTag());
        QueryWrapper<Classification> classificationQueryWrapper = new QueryWrapper<>();
        classificationQueryWrapper.eq("classifyName", blog1.getTag());
        Classification classification = classificationMapper.selectOne(classificationQueryWrapper);
        blogClassification.setClassifyId(classification.getId());
        blogClassification.setBlogId(blog1.getId());
        blogClassificationMapper.insert(blogClassification);
        if (pd == 1) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 通过openid查询用户博客
     *
     * @param openId
     * @return 博客列表
     */
    public List<Blog> findBlogByOpenid(String openId) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("openid", openId);
        List<User> userlist = userMapper.selectList(userQueryWrapper);
        User user = userlist.get(0);
        int userId = user.getId();
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq("userId", userId);
        return blogMapper.selectList(blogQueryWrapper);
    }

    /**
     * 通过openid查询用户博客
     *
     * @param
     * @return 博客列表
     */
    public List<Blog> getCollectListByOpenid(String openid1) {
        // 获取用户userid
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("openid", openid1);
        List<User> userlist = userMapper.selectList(userQueryWrapper);
        User user = userlist.get(0);
        int userId = user.getId();
        String nikename = user.getNickname();
        // 获取博客blogid
        QueryWrapper<UserCollection> userCollectionQueryWrapper = new QueryWrapper<>();
        userCollectionQueryWrapper.eq("userId", userId);
        List<UserCollection> userCollections = userCollectionMapper.selectList(userCollectionQueryWrapper);
        ArrayList<Blog> blogList = new ArrayList<>();
        for (UserCollection userCollection : userCollections) {
            int blogid = userCollection.getBlogId();
            QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
            blogQueryWrapper.eq("id", blogid);
            Blog blog = blogMapper.selectOne(blogQueryWrapper);
            blogList.add(blog);
        }
        return blogList;
    }

    /**
     * 分页查询获取所有博客信息
     *
     * @return blogList
     */
    public ipageBlog getAllBlogInfo(int page1, int PAGE_RECORDS_NUM, String query) {
        List<Blog> userList = new ArrayList<Blog>();
        // 设置条件构造器
        QueryWrapper<Blog> wrapper = new QueryWrapper<>();
        wrapper.like("title", query);
        // 构造分页信息，其中的Page<>(page, PAGE_RECORDS_NUM)的第一个参数是页数，而第二个参数是每页的记录数
        IPage<Blog> blogPage = new Page<>(page1, PAGE_RECORDS_NUM);
        // page(postPage, wrapper)这里的第一个参数就是上面定义了的Page对象，第二个参数就是上面定义的条件构造器对象，通过调用这个方法就可以根据你的分页信息以及查询信息获取分页数据
        IPage<Blog> blog1IPage = blogMapper.selectPage(blogPage, wrapper);
        // 封装数据，其中getRecords()是获取记录数，getCurrent()获取当前页数，getPages()获取总页数，getTotal()获取记录总数，还要其他更多的方法，大家可以自行查看，在这里就不过多赘述了
        userList = blog1IPage.getRecords();
        Long total = blog1IPage.getTotal();
        ipageBlog ipageBlog = new ipageBlog();
        ipageBlog.setBlogList(userList);
        ipageBlog.setTotal(total.intValue());
        return ipageBlog;
    }

    /**
     * 删除通过id博客
     *
     * @param id
     * @return 是否删除
     */
    public int deleteByid(Integer id) {
        int result = blogMapper.deleteById(id);
        return result;
    }

    /**
     * 通过blogId 获取博客
     *
     * @param id
     * @return 博客
     */
    public Blog getBlogById(Integer id) {
        Blog blog = blogMapper.selectById(id);
        return blog;
    }

    /**
     * 保存博客信息
     *
     * @param
     * @return
     */
    public int saveInfoByid(Blog blog) {
        QueryWrapper<Blog> wrapper = new QueryWrapper<>();
        wrapper.eq("id", blog.getId());
        Blog blog1 = blogMapper.selectOne(wrapper);
        blog1.setTag(blog.getTag());
        blog1.setTitle(blog.getTitle());
        blog1.setAuthor(blog.getAuthor());
        UpdateWrapper blogUpdateWrapper = new UpdateWrapper();
        blogUpdateWrapper.eq("id", blog.getId());
        return blogMapper.update(blog1, blogUpdateWrapper);
    }

    /**
     * 分页查询博客
     *
     * @param pagenum  当前数量
     * @param pagesize 查询数量
     * @return 集合
     */
    public ipageBlog getPageBlogByHots(String pagenum, String pagesize, String provinceName) {
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.orderByDesc("thumbs");
        Page<Blog> page = new Page<>(Long.parseLong(pagenum), Long.parseLong(pagesize));
        if ("全部".equals(provinceName)) {
            blogMapper.selectPage(page, blogQueryWrapper);
        } else {
            blogQueryWrapper.eq("provinceName", provinceName);
            blogMapper.selectPage(page, blogQueryWrapper);
        }
        List<Blog> blogList = page.getRecords();
        for (Blog blog : blogList) {
            User user = userMapper.selectById(blog.getUserId());
            blog.setUser(user);
        }
        long total = page.getTotal();
        ipageBlog ipageBlog = new ipageBlog();
        ipageBlog.setBlogList(blogList);
        ipageBlog.setTotal((int) total);
        return ipageBlog;
    }

    /**
     * 通过点赞量获取博客
     *
     * @return 博客列表
     */
    public List<Blog> getBlogByThumb() {
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("thumbs");
        List<Blog> blogList = blogMapper.selectList(queryWrapper);
        for (Blog blog : blogList) {
            User user = userMapper.selectById(blog.getUserId());
            blog.setUser(user);
        }
        return blogList;
    }

    /**
     * 通过标签获取博客
     *
     * @return 博客列表
     */
    public List<Blog> getBlogByTag(String tag) {
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tag", tag);
        List<Blog> blogList = blogMapper.selectList(queryWrapper);
        return blogList;
    }

    /**
     * 通过点赞量和搜索词获取博客
     *
     * @return 博客列表
     */
    public List<Blog> getBlogByValue(String value) {
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        if (value != null) {
            queryWrapper.like("title", value).or().like("tag", value);
        }

        queryWrapper.orderByDesc("thumbs");
        List<Blog> blogList = blogMapper.selectList(queryWrapper);
        for (Blog blog : blogList) {
            User user = userMapper.selectById(blog.getUserId());
            blog.setUser(user);
        }
        return blogList;
    }

    /**
     * 根据用户id查询博客数量
     * @param userId 用户id
     * @return 数量
     */
    public int getBlogCountById(String userId) {
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq("userId",userId);
        return blogMapper.selectCount(blogQueryWrapper);
    }

    /**
     * 根据用户id查询博客
     * @param userId 用户id
     * @return 博客集合
     */
    public List<Blog> findBlogByUserId(String userId) {
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq("userId",userId);
        return blogMapper.selectList(blogQueryWrapper);
    }
}
